package com.lsu.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsu.app.bean.Notice;
import com.lsu.app.config.target.RequestRoles;
import com.lsu.app.service.*;
import com.lsu.app.tool.R;
import com.lsu.app.tool.jiebaUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Set;

/**
 * @author hjj
 * @date 2023/11/2 17:56
 */
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/mails")
public class MailController {
    @Autowired
    private HttpServletRequest request;
    private  final UserService userService;
    private  final ResourceService resourceService;
    private final NoticeService noticeService;
    private  final CourseService courseService;
    private final LogService logService;
    private final VocabularyService vocabularyService;

    public MailController(UserService userService, ResourceService resourceService, NoticeService noticeService, CourseService courseService, LogService logService, VocabularyService vocabularyService) {
        this.userService = userService;
        this.resourceService = resourceService;
        this.noticeService = noticeService;
        this.courseService = courseService;
        this.logService = logService;
        this.vocabularyService = vocabularyService;
    }
    @RequestRoles({"teacher","student"})
    @GetMapping("/getSendNotice")
    @ApiOperation("发件人获取自己发送的邮箱简洁信息")
    public R<Page<Notice>> getSendNotice(
        @ApiParam("当前页")@RequestParam("pageCur") Integer pageCur,
        @ApiParam("页码")@RequestParam("pageSize") Integer pageSize
    ){
        Integer userId = (Integer) request.getSession().getAttribute("id");
        Page<Notice> noticePage = noticeService.page(new Page<>(pageCur,pageSize),new LambdaQueryWrapper<Notice>().eq(Notice::getRelateId,userId));
        for (Notice record : noticePage.getRecords()) {
            record.setRelateImgUrl(resourceService.getHeadUrlByUorrIdAndType(record.getRelateId()));
            record.setTargetName(courseService.getCourseNameById(record.getTargetId()));
            record.setTargetUserImgUrl(resourceService.getHeadUrlByUorrIdAndType(record.getTargetUserId()));
            record.setTargetUserNicName(userService.getNameById(record.getTargetUserId()));
        }
        return R.success(noticePage);
    }


    @RequestRoles({"teacher","student"})
    @GetMapping("/getTeaNotice/{state}")
    @ApiOperation("收件人获取邮箱简洁信息[id+资源名称+类型]")
    public R<Page<Notice>> getPageNotice(
            @ApiParam("当前页")@RequestParam("pageCur") Integer pageCur,
            @ApiParam("页码")@RequestParam("pageSize") Integer pageSize,
            @ApiParam("信息状态[1未读，2已读，0已删除]")@PathVariable("state")Integer state
    ){
        Integer id = (Integer) request.getSession().getAttribute("id");
        Page<Notice> noticePage = noticeService.page(new Page<>(pageCur,pageSize),new LambdaQueryWrapper<Notice>().eq(Notice::getTargetUserId,id).eq(Notice::getState,state));
        for (Notice record : noticePage.getRecords()) {
            record.setRelateName(userService.getNameById(record.getRelateId()));//发送者昵称
            record.setTargetName(courseService.getCourseNameById(record.getTargetId()));//课程课程名称
            record.setRelateImgUrl(resourceService.getHeadUrlByUorrIdAndType(record.getRelateId()));//发送者头像
            record.setTargetUserImgUrl(resourceService.getHeadUrlByUorrIdAndType(record.getTargetUserId()));//接收者头像
            record.setTargetUserNicName(userService.getNameById(record.getTargetUserId()));//接收者昵称
        }
        return R.success(noticePage);
    }
    @RequestRoles({"teacher","student"})
    @GetMapping("/getNoticeById")
    @ApiOperation("收件人/发件人获取未读通知详细信息[收件人使用这个接口后，该通知变成已读]")
    public R<Notice> getNotice(
            @ApiParam("通知id")@RequestParam("id") Integer id
    ){
        Notice notice = noticeService.getById(id);
        if(notice==null){
            return R.err("该通知不存在");
        }
        notice.setRelateName(userService.getNameById(notice.getRelateId()));//发送者昵称
        notice.setTargetName(courseService.getCourseNameById(notice.getTargetId()));//课程课程名称
        notice.setRelateImgUrl(resourceService.getHeadUrlByUorrIdAndType(notice.getRelateId()));//发送者头像
        notice.setTargetUserImgUrl(resourceService.getHeadUrlByUorrIdAndType(notice.getTargetUserId()));//接收者头像
        notice.setTargetUserNicName(userService.getNameById(notice.getTargetUserId()));//接收者昵称

        //如果是收件人调用这个，信息设成已读
        Integer userId = (Integer) request.getSession().getAttribute("id");
        if (notice.getTargetUserId()==userId){
            noticeService.update(new LambdaUpdateWrapper<Notice>().eq(Notice::getId,id).set(Notice::getState,2));
            if(notice.getTargetId()!=0){
                //将关键词存入数据库
                vocabularyService.insertData(notice.getRelateId(),notice.getTargetId(), jiebaUtil.getSignaleWord(notice.getContent()));
            }
        }
        return R.success(notice);
    }

    @RequestRoles({"teacher","student"})
    @PostMapping("/createNotice")
    @ApiOperation("发件人创建邮件信息")
    public R<Notice> createNotice(
            @ApiParam("通知类型（1课程提醒，2课程反馈，3消息回复[用户对用户]）")@RequestParam("type") Integer type,
            @ApiParam("课程id")@RequestParam("targetId") Integer targetId,
            @ApiParam("回复用户id")@RequestParam(value = "userId",required = false) Integer userId,
            @ApiParam("标题")@RequestParam("title") String title,
            @ApiParam("内容")@RequestParam("content") String content
    ){
        if(title.equals("")){
            return R.err("标题不为空");
        }
        if(content.equals("")){
            return R.err("内容不为空");
        }
        Integer id = (Integer) request.getSession().getAttribute("id");
        Integer targetUserId = courseService.getTeacherIdByCourseId(targetId);
        Notice newNotice = new Notice(type,id,title,content,targetId,targetUserId,1, LocalDateTime.now().toString());
        newNotice.setRelateName(userService.getNameById(id));
        newNotice.setTargetName(courseService.getCourseNameById(targetId));
        newNotice.setRelateImgUrl(resourceService.getHeadUrlByUorrIdAndType(id));
        if(type==1||type==2){
            newNotice.setTargetUserImgUrl(resourceService.getHeadUrlByUorrIdAndType(targetUserId));
        }else if (userId!=null&&userId!=0&&type==3){
            newNotice.setTargetUserId(userId);
            newNotice.setTargetUserImgUrl(resourceService.getHeadUrlByUorrIdAndType(userId));
        }
        noticeService.save(newNotice);
        newNotice.setRelateName(userService.getNameById(id));
        newNotice.setTargetName(courseService.getCourseNameById(targetId));
        newNotice.setRelateImgUrl(resourceService.getHeadUrlByUorrIdAndType(id));
        return R.success(newNotice);
    }
    @RequestRoles({"teacher"})
    @PostMapping("/sends")
    @ApiOperation("教师群发信息(根据课程id)给反馈的学生")
    public R<String> sends(
        @ApiParam("课程id")@RequestParam("targetId") Integer targetId,
        @ApiParam("标题")@RequestParam("title") String title,
        @ApiParam("内容")@RequestParam("content") String content
    ){
        Integer teacherId = (Integer) request.getSession().getAttribute("id");
        Set<Integer> ids = noticeService.getStudentIdsByCourseId(targetId);
        String time = LocalDateTime.now().toString();
        for (Integer id : ids) {
            noticeService.save(new Notice(3,teacherId,title,content,targetId,id,1,time));
        }
        return R.success("发送成功");
    }

    @RequestRoles({"teacher","student"})
    @DeleteMapping("/deleteNotice")
    @ApiOperation("发件人/收件人-删除邮件")
    public R<String> deleteNotice(
        @ApiParam("邮件id")@RequestParam("id") Integer id
    ){
        Integer userId = (Integer) request.getSession().getAttribute("id");
        Notice notice = noticeService.getById(id);
         if(notice.getRelateId()==userId){//发件人删除
             if (notice.getRelateId()==notice.getTargetUserId()){
                 noticeService.removeById(id);
             }
            if(notice.getState()==1){//如果收件人未读，则真删除
                noticeService.removeById(id);
                logService.createLog("MAIL_DELETE","delete-"+notice.getTitle(),"user-"+request.getSession()
                        .getAttribute("username"));
                return R.success("撤销发送成功");
            }else{
                noticeService.update(new LambdaUpdateWrapper<Notice>().eq(Notice::getId,id).set(Notice::getState,0));
                return R.success("状态设置成功");
            }
        }else if(notice.getTargetUserId()==userId){ //收件人状态删除
            noticeService.update(new LambdaUpdateWrapper<Notice>().eq(Notice::getId,id).set(Notice::getState,0));
            logService.createLog("MAIL_DEAD_DELETE","delete-"+notice.getTitle(),"user-"+request.getSession()
                    .getAttribute("username"));
            return R.success("删除成功");
        }
        return R.err("无权删除");
    }


}
